<template>
	<view>
		<wrapImgBg />

		<topHeader :navigationTitle="navigationTitle" :city="district" :keywords.sync="keyword" @onSearch="onRefresh" />

		<view class="wrap flex column">
			<categoryList v-if="category_list.length > 0" :list="category_list" />

			<articleList :list="list" />
		</view>
	</view>
</template>

<script>
	import { getArticleList } from "@/API/article.js";
	import topHeader from "@/components/navigationBar/articleNavigationBar.vue";
	import wrapImgBg from "@/components/navigationBar/bgImg.vue";
	import categoryList from "@/components/article/categoryList.vue";
	import articleList from "@/components/article/articleList.vue";
	import event from "@/utils/event.js";
	
	export default {
		components: {
			topHeader,
			wrapImgBg,
			categoryList,
			articleList,
		},
		data() {
			return {
				navigationTitle: "", // 导航栏标题
				province: "", //省份
				city: "", //市
				district: "", //区
				lat: "",
				lng: "",
				parent_id: "", // 一级分类id
				category_list: [], // 分类列表
				keyword: "", // 搜索关键字

				page: 1, // 当前页码
				total: 0, //总数
				list: [], //列表
			};
		},
		onLoad(options) {
			this.navigationTitle = options.title;
			this.parent_id = options.parent_id;
			
			const locationInfo = this.$stoarge.getChangeCity();
			if (locationInfo) {
				this.province = locationInfo.province;
				this.city = locationInfo.city;
				this.district = locationInfo.district;
				this.lat = locationInfo.lat;
				this.lng = locationInfo.lng;
			}
			
			this.getCategoryList();
			this.onRefresh();
		},
		onReady() {
			event.on("onSureChooseCity", this, res => {
				this.province = res.province;
				this.city = res.city;
				this.district = res.district;
				this.lat = res.lat;
				this.lng = res.lng;
				
				this.onRefresh();
			})
		},
		onPullDownRefresh() {
			this.onRefresh();
		},
		onReachBottom() {
			if (this.list.length < this.total) {
				this.page++;
				this.getData();
			}
		},
		onUnload() {
			event.remove("onSureChooseCity", this);
		},
		methods: {
			/**
			 * 刷新
			 */
			onRefresh() {
				this.page = 1;
				this.getData();
			},
			/**
			 * 网络请求
			 */
			getData() {
				getArticleList({
					page: this.page,
					category_id: this.parent_id,
					keyword: this.keyword,
					city: [this.province, this.city, this.district].join("/"),
					lat: this.lat,
					lng: this.lng
				}).then((res) => {
					const list = res.data.data;
					if (this.page === 1) {
						this.total = res.data.total;
						this.list = list;
					} else {
						this.list = this.list.concat(list);
					}
				});
			},
			/**
			 * 获取分类
			 */
			getCategoryList() {
				this.$commonNetwork.getArticleCategoryList(this.parent_id, (list) => {
					this.category_list = list;
				});
			},
		},
	};
</script>

<style scoped>
	.wrap {
		padding: 0rpx 25rpx;
		box-sizing: border-box;
		gap: 18rpx;
	}
</style>
